﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Office.Interop.Word;
using TemplateGenerator.Logic;
using System.Threading.Tasks;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using Novacode;

namespace TemplateGenerator {
	public static class GeneratorHandler
    {

		public static Microsoft.Office.Interop.Word.Application WordApp;

        public static void FormatDocument(System.Data.DataTable fieldNValues)
        {
            FolderBrowserDialog save = new FolderBrowserDialog();

            if (save.ShowDialog() == DialogResult.OK)
            {
                List<Dictionary<string, string>> inputData = CreateFieldDictionary(fieldNValues);

                DirectoryInfo direcotryInfo = CreateEmptyFiles(fieldNValues, save);

                List<templateT> template = new List<templateT>();

                FileInfo[] files = direcotryInfo.GetFiles();
                for(int i = 0; i < files.Length; i++)
                    template.Add(new templateT(inputData[i], files[i]));

                PovoateFiles(template);

                RemoveTemporaryFiles(save.SelectedPath, direcotryInfo);
            }

        }

        private static void RemoveTemporaryFiles(string path, DirectoryInfo direcotryInfo)
        {
            
            //now move all the files inside tmp and delete tmp
            foreach (FileInfo file in direcotryInfo.GetFiles())
            {
                File.Move(file.FullName, path + "\\" +  file.Name);
            }

            Directory.Delete(path + "\\temp");
        }

        private static void PovoateFiles(List<templateT> save)
        {
            // Loop through each document in this specified direction.
            Parallel.ForEach(save, template =>
            {
                // Load the document.
                using (DocX document = DocX.Load(template.file.FullName))
                {
                    foreach (KeyValuePair<string, string> value in template.dictionary)
                        document.ReplaceText(value.Key, value.Value);

                    // Save changes made to this document.
                    document.Save();
                } // Release this document from memory.
            });
        }

        private static DirectoryInfo CreateEmptyFiles(System.Data.DataTable fieldNValues, FolderBrowserDialog save)
        {
            Word.Document document = WordApp.ActiveDocument;

            object missing = System.Reflection.Missing.Value;
            object name = save.SelectedPath + "\\template.docx";

            document.SaveAs(ref name, ref missing, ref missing, ref missing, ref missing, ref missing,
                      ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                      ref missing, ref missing, ref missing, ref missing);

            Directory.CreateDirectory(save.SelectedPath + "\\temp\\");

            //creates all the documents that will be modified.
            for (int i = 0; i < fieldNValues.Rows.Count; i++)
            {
                string file = fieldNValues.Rows[i][0].ToString();

                Array.ForEach(Path.GetInvalidFileNameChars(),  c => file = file.Replace(c.ToString(), String.Empty));

                string trim = file.Replace(" ", "");
                trim = trim.Replace("r", "");
                trim = trim.Replace("n", "");
                trim = trim.Replace("t", "");


                string destination = save.SelectedPath + "\\temp\\" +  file + ".docx";

                if (File.Exists(destination))
                    File.Delete(destination);
                File.Copy(name.ToString(), destination);
     

            }

            DirectoryInfo directoryInfo = new DirectoryInfo(save.SelectedPath + "\\temp\\");
            return directoryInfo;
        }

        private static List<Dictionary<string, string>> CreateFieldDictionary(System.Data.DataTable fieldNValues)
        {
            List<Dictionary<string, string>> dictionary = new List<Dictionary<string, string>>();
           
            for (int i = 0; i < fieldNValues.Rows.Count; i++)
            {
                Dictionary<string, string> inputData = new System.Collections.Generic.Dictionary<string, string>();

                for (int j = 0; j < fieldNValues.Columns.Count; j++)
                    inputData.Add(fieldNValues.Columns[j].ToString(), fieldNValues.Rows[i][j].ToString());

                dictionary.Add(inputData);
            }

            return dictionary;
        }

	}
}
